<template>
  <a-spin :spinning="loading" class="page-miH page-bgBack">
    <PageHeader @back="goBack" subTitle="返回">
      {{ item.billName }}
    </PageHeader>
    <div class="page">
      <div style="display:flex;justify-content: space-between">
        <div class="fix-item-wrapper">
          <div class="fix-item-one">
            <p class="fix-item-name">合计</p>
          </div>
          <div class="fix-item-two">
            <div style="margin-top:20px;">
              <p class="childpProjectName">
                {{ getTitle(item.subjectType, 0) === "计薪人数" ? "计薪人数" : "人数" }}
              </p>
              <p class="childContentName">
                {{ item ? (getTitle(item.subjectType, 0) === "计薪人数" ? getCost(item, 0) : item.number) : "0" }}
              </p>
            </div>
          </div>
        </div>
        <div class="fix-item-wrapper2">
          <div class="fix-item-two" v-if="getTitle(item.subjectType, 0) !== '计薪人数'">
            <div>
              <p class="childpProjectName">{{ item ? getTitle(item.subjectType, 0) : "" }}</p>
              <p class="childContentName">
                {{ item ? (getTitle(item.subjectType, 0) === "计薪人数" ? getCost(item, 0) + "人" : "¥" + getCost(item, 0) + "元") : "" }}
              </p>
            </div>
          </div>
          <div v-if="getTitle(item.subjectType, 0) !== '计薪人数'" style="border-right: 1px solid #e8e8e8;margin-bottom:20px;"></div>

          <div class="fix-item-two">
            <p class="childpProjectName">{{ item ? getTitle(item.subjectType, 1) : "" }}</p>
            <p class="childContentName">¥{{ item ? getCost(item, 1) : "" }}元</p>
          </div>
          <div style="border-right: 1px solid #e8e8e8;margin-bottom:20px;"></div>

          <div class="fix-item-two" v-if="item.subjectType === '社保账单' || item.subjectType === '公积金账单'">
            <div>
              <p class="childpProjectName">滞纳金</p>
              <p class="childContentName">¥{{ item.fine ? item.fine : 0 }}元</p>
            </div>
          </div>
          <div
            v-if="item.subjectType === '社保账单' || item.subjectType === '公积金账单'"
            style="border-right: 1px solid #e8e8e8;margin-bottom:20px;"
          ></div>

          <div class="fix-item-two">
            <div>
              <p class="childpProjectName">{{ item ? getTitle(item.subjectType, 2) : "" }}</p>
              <p class="childContentName">¥{{ item ? getCost(item, 2) : "" }}元</p>
            </div>
          </div>
          <div style="border-right: 1px solid #e8e8e8;margin-bottom:20px;"></div>
          <div class="fix-item-two" v-if="item.isConfirm">
            <div>
              <p class="childpProjectName">实际支付金额</p>
              <p class="childContentName">¥{{ item.finalAmount ? item.finalAmount : 0 }}元</p>
            </div>
          </div>
        </div>
      </div>
      <div class="operation">
        <div>
          <a-input-search allow-clear class="mr12" placeholder="姓名/身份证号" style="width: 180px" @search="inputChange" />
          <a-select v-if="item.isMerge" style="width: 200px" placeholder="用工单位" allow-clear @change="handleChange">
            <a-select-option v-for="(item, index) in templatesList" :key="index" :value="index">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </div>

        <div>
          <a-button
            :disabled="(item.approStatus !== 5 && item.approStatus !== 0) || item.isMerge"
            @click="
              () => {
                BillConfirm = true;
              }
            "
            type="primary"
            ghost
            >账单结算</a-button
          >
          <a-button style="margin-left:15px" @click="() => download()" type="primary" ghost>全部导出</a-button>
          <a-button
            :disabled="item.approStatus === 1 || item.approStatus === 3"
            type="primary"
            ghost
            style="margin-left:15px"
            @click="shengpiHand"
          >
            发起审批
          </a-button>
        </div>
      </div>
      <div class="tableBox">
        <a-table
          row-key="defaultType"
          :columns="columns"
          :data-source="dataList"
          :pagination="pagination"
          @change="handleTableChange"
          :scroll="{ x: 1200 }"
        >
        </a-table>
      </div>
    </div>
    <a-modal title="发起审批" :visible="isMergConfirmPlan" width="500px" :destroy-on-close="true" @cancel="handleCancel">
      <template slot="footer">
        <a-button @click="handleCancel"> 取消 </a-button>
        <a-button key="submit" type="primary" @click="mergConfirmOk">
          确定
        </a-button>
      </template>
      <div>
        <a-form :label-col="{ span: 9 }" :wrapper-col="{ span: 12 }">
          <a-form-item label="账单时间" required>
            <div
              style="font-size: 14px;
    font-weight: 500;color: #000;"
            >
              {{ item.year + "年" + item.month + "月" }}
            </div>
          </a-form-item>
          <a-form-item label="审批账单类型" required>
            <div
              style="font-size: 14px;
    font-weight: 500;color: #000;"
            >
              {{ item.subjectType }}
            </div>
          </a-form-item>
          <a-form-item label="用工单位" required>
            <a-select style="width: 220px" placeholder="请选择用工单位" @change="handleCompyChange" v-model="companyId">
              <a-select-option v-for="(item, index) in comanyListGroup" :key="index" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="账单审批模板" required>
            <a-select
              v-model="tempTemplate"
              style="width: 220px"
              placeholder="请选择审批模板"
              @change="handleChange2"
              :disabled="!companyId"
            >
              <a-select-option v-for="(item, index) in templatesListGroup" :key="index" :value="item.id">
                {{ item.typeName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <a-modal title="账单结算" :visible="BillConfirm" width="560px" :destroy-on-close="true" @cancel="handleCancel">
      <template slot="footer">
        <a-button @click="handleCancel"> 取消 </a-button>
        <a-button key="submit" type="primary" @click="BillConfirmOk">
          确定
        </a-button>
      </template>
      <div>
        <div
          style="display: flex;
    align-items: center;
    justify-content: center;margin-bottom:20px;font-size:15px;font-weight:700;"
        >
          {{ item ? item.tempCompanyName + item.billName : "" }}
        </div>
        <a-form :label-col="{ span: 7 }" :wrapper-col="{ span: 12 }">
          <a-form-item label="人数" v-if="item ? getTitle(item.subjectType, 0) !== '计薪人数' : false">
            <a-input
              suffix="人"
              :disabled="true"
              :default-value="item ? (getTitle(item.subjectType, 0) !== '计薪人数' ? item.number : getCost(item, 0)) : 0"
            />
          </a-form-item>
          <a-form-item :label="item ? getTitle(item.subjectType, 0) : ''">
            <a-input suffix="元" :disabled="true" :default-value="item ? getCost(item, 0) : 0" />
          </a-form-item>
          <a-form-item :label="item ? getTitle(item.subjectType, 1) : ''">
            <a-input suffix="元" :disabled="true" :default-value="item ? getCost(item, 1) : 0" />
          </a-form-item>
          <a-form-item :label="item ? getTitle(item.subjectType, 2) : ''">
            <a-input suffix="元" :disabled="true" :default-value="item ? getCost(item, 2) : 0" />
          </a-form-item>
          <a-form-item label="实际付款额">
            <a-input-number :min="0" suffix="元" :default-value="onBillChange(item ? getCost(item, 2) : 0)" @change="onBillChange" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </a-spin>
</template>
<script>
import {
  costBillInfo,
  launchApproval,
  listAllCompanyId,
  getModelList,
  selectCompanyByCostBillId,
  confirmCostBill
} from "@/api/billing/billing";

const columns = [];
import moment from "moment";
import axios from "axios";
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      zongBill: 0,
      tempTemplate: undefined,
      comanyListGroup: [],
      BillConfirm: false,
      isMergConfirmPlan: false,
      templatesList: [],
      templatesListGroup: [],
      item: undefined,
      dataList: [],
      tempList: [],
      columns,
      size: "default",
      loading: false,
      monthly: moment().format("MM"),
      yearly: moment().format("YYYY"),
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: total => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        personalPeriod: null
      },
      companyId: undefined
    };
  },
  created() {
    this.item = JSON.parse(this.$route.query.item);
    this.getBillInfo();
    if (this.item.isMerge) {
      listAllCompanyId({ costBillId: this.item.id }).then(res => {
        this.templatesList = res.data;
      });
    }
  },
  computed: {
    ...mapGetters(["permissions_site"])
  },
  methods: {
    onBillChange(value) {
      this.zongBill = value;
      return value;
    },

    BillConfirmOk() {
      if (this.item) {
        const param = {
          costBillId: this.item.id,
          finalAmount: this.zongBill
        };

        confirmCostBill(param).then(res => {
          this.handleCancel();
          if (res.success) {
            this.$message.success("账单已结算");
            this.item.approStatus = 6;
          }
        });
      }
    },
    handleCompyChange(id) {
      this.companyId = id;
      this.templatesListGroup = [];
      this.tempTemplate = undefined;
      let type;
      if (this.item.subjectType === "社保账单") {
        type = "socBill";
      } else if (this.item.subjectType === "公积金账单") {
        type = "pfBill";
      } else if (this.item.subjectType === "薪资账单") {
        type = "salaryBill";
      }
      // 根据公司查询模板
      getModelList(id, type).then(res => {
        this.templatesListGroup = res.data;
        if (this.templatesListGroup.length !== 0) {
          this.tempTemplate = this.templatesListGroup[0].id;
        } else {
          this.tempTemplate = undefined;
        }
      });
    },
    handleChange2(id) {
      // 选择模板
      this.tempTemplate = id;
    },
    mergConfirmOk() {
      // 发起审批
      if (!this.companyId) {
        this.$message.success("请选择用工单位");
        return;
      }
      if (!this.tempTemplate) {
        this.$message.success("请选择审批模板");
        return;
      }
      this.isMergConfirmPlan = false;
      launchApproval({
        companyId: this.companyId,
        costBillId: this.item.id,
        flowId: this.tempTemplate
      }).then(res => {
        this.item.approStatus = res.data.status;
        this.$message.success("已发起审批");
      });
    },
    handleCancel() {
      this.isMergConfirmPlan = false;
      this.BillConfirm = false;
    },
    handleChange(index) {
      this.pagination.current = 1;
      if (index) {
        var count = this.tempList.length;
        var filterList = [];
        for (var i = 0; i < count; i++) {
          if (this.tempList[i]["用工单位"] === this.templatesList[index].name) {
            filterList.push(this.tempList[i]);
          }
        }
        this.dataList = filterList;
      } else {
        this.dataList = this.tempList;
      }
      this.pagination.total = this.dataList.length;
    },
    shengpiHand() {
      this.isMergConfirmPlan = true;

      this.companyId = undefined;
      this.tempTemplate = undefined;
      // 拉取账单的用工单位
      selectCompanyByCostBillId({ costBillId: this.item.id }).then(res => {
        this.comanyListGroup = res.data;
        if (this.comanyListGroup.length !== 0) {
          this.companyId = this.comanyListGroup[0].id;

          // 拉取模板
          this.handleCompyChange(this.companyId);
        } else {
          this.companyId = undefined;
        }
      });
    },
    getBillInfo() {
      this.loading = true;
      this.columns = [];
      costBillInfo(this.item.id)
        .then(res => {
          // console.log(res.data);

          const count = res.data.headList.length;

          // 姓名
          this.columns.push({
            title: "员工姓名",
            dataIndex: "员工姓名",
            key: "员工姓名",
            fixed: "left",
            ellipsis: true,
            width: 120
          });
          this.columns.push({
            title: "身份证号",
            dataIndex: "身份证号",
            key: "身份证号",
            ellipsis: true,
            width: 170
          });
          for (var i = 0; i < count; i++) {
            if (
              res.data.headList[i] !== "个人社保合计" &&
              res.data.headList[i] !== "单位社保合计" &&
              res.data.headList[i] !== "个人公积金合计" &&
              res.data.headList[i] !== "单位公积金合计"
            ) {
              this.columns.push({
                title: res.data.headList[i],
                dataIndex: res.data.headList[i],
                key: res.data.headList[i],
                ellipsis: true,
                width: 120
              });
            }
          }
          if (this.item.subjectType === "薪资账单") {
            this.columns.push({
              title: "实发工资",
              dataIndex: "实发工资",
              key: "实发工资",
              fixed: "right",
              ellipsis: true,
              width: 130
            });
            // this.columns.push({
            //   title: "个人所得税",
            //   dataIndex: "个人所得税",
            //   key: "个人所得税",
            //   fixed: "right",
            //   ellipsis: true,
            //   width: 130
            // });
          } else if (this.item.subjectType === "社保账单") {
            this.columns.push({
              title: "个人社保合计",
              dataIndex: "个人社保合计",
              key: "个人社保合计",
              fixed: "right",
              ellipsis: true,
              width: 140
            });
            this.columns.push({
              title: "单位社保合计",
              dataIndex: "单位社保合计",
              key: "单位社保合计",
              fixed: "right",
              ellipsis: true,
              width: 140
            });
            this.columns.push({
              title: "总缴费",
              dataIndex: "总缴费",
              key: "总缴费",
              fixed: "right",
              ellipsis: true,
              width: 100
            });
          } else if (this.item.subjectType === "公积金账单") {
            this.columns.push({
              title: "个人公积金合计",
              dataIndex: "个人公积金合计",
              key: "个人公积金合计",
              fixed: "right",
              ellipsis: true,
              width: 140
            });
            this.columns.push({
              title: "单位公积金合计",
              dataIndex: "单位公积金合计",
              key: "单位公积金合计",
              fixed: "right",
              ellipsis: true,
              width: 140
            });
            this.columns.push({
              title: "总缴费",
              dataIndex: "总缴费",
              key: "总缴费",
              fixed: "right",
              ellipsis: true,
              width: 100
            });
          }

          var datalength = res.data.infoList.length;
          for (var j = 0; j < datalength; j++) {
            const obj = {};
            for (var key in res.data.infoList[j].headDate) {
              obj[key] = res.data.infoList[j].headDate[key] ? res.data.infoList[j].headDate[key] : 0;
            }
            obj["员工姓名"] = res.data.infoList[j].name;
            obj["身份证号"] = res.data.infoList[j].idCard;
            if (this.item.subjectType !== "薪资账单") {
              obj["总缴费"] = res.data.infoList[j].totalAmount;
            } else {
              // obj["个人所得税"] = res.data.infoList[j].tax;
              obj["实发工资"] = res.data.infoList[j].totalAmount;
            }

            this.dataList.push(obj);
          }
          this.tempList = this.dataList;
          this.pagination.total = this.dataList.length;
          this.loading = false;
        })
        .catch(err => {
          console.log("debug log --> ", err);

          this.loading = false;
        });
    },
    getTitle(value, index) {
      switch (value) {
        case "社保账单":
          if (index === 0) {
            return "个人社保";
          } else if (index === 1) {
            return "单位社保";
          } else if (index === 2) {
            return "总缴费";
          } else {
            break;
          }
        case "公积金账单":
          if (index === 0) {
            return "个人公积金";
          } else if (index === 1) {
            return "单位公积金";
          } else if (index === 2) {
            return "总缴费";
          } else {
            break;
          }
        case "薪资账单":
          if (index === 0) {
            return "计薪人数";
          } else if (index === 1) {
            return "总缴税";
          } else if (index === 2) {
            return "总实发工资";
          } else {
            break;
          }
      }
    },
    getCost(value, index) {
      switch (value.subjectType) {
        case "社保账单":
          if (index === 0) {
            return value.personalSocAmount;
          } else if (index === 1) {
            return value.companySocAmount;
          } else if (index === 2) {
            return value.totalAmount;
          } else {
            break;
          }
        case "公积金账单":
          if (index === 0) {
            return value.personalPfAmount;
          } else if (index === 1) {
            return value.companyPfAmount;
          } else if (index === 2) {
            return value.totalAmount;
          } else {
            break;
          }
        case "薪资账单":
          if (index === 0) {
            return value.calculateSalaryNumber ? value.calculateSalaryNumber : 0;
          } else if (index === 1) {
            return value.totalTax ? value.totalTax : 0;
          } else if (index === 2) {
            return value.totalAmount ? value.totalAmount : 0;
          } else {
            break;
          }
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    download() {
      const token = this.$store.state.auth.token;

      axios({
        url: `/hr/api/v1/costBills/export/` + this.item.id,
        method: "post",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then(res => {
          if (res.data && res.data.type === "application/json") {
            const reader = new FileReader();
            reader.readAsText(res.data, "utf-8");
            reader.onload = () => {
              const resJson = JSON.parse(reader.result);
              this.$message.error(resJson.msg);
            };
          } else {
            const blob = new Blob([res.data], {
              type: "application/octet-stream"
            });
            const link = document.createElement("a");
            try {
              link.download = this.item.billName + ".xlsx";
            } catch (err) {
              console.log("debug log --> ", res);
            }
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        })
        .catch(err => {
          console.log("debug log --> ", err);
        });
    },

    inputChange(e) {
      this.pagination.current = 1;
      if (e) {
        var count = this.tempList.length;
        var filterList = [];
        for (var i = 0; i < count; i++) {
          if (
            (this.tempList[i]["员工姓名"] && this.tempList[i]["员工姓名"].indexOf(e) !== -1) ||
            (this.tempList[i]["身份证号"] && this.tempList[i]["身份证号"].indexOf(e) !== -1)
          ) {
            filterList.push(this.tempList[i]);
          }
        }
        this.dataList = filterList;
      } else {
        this.dataList = this.tempList;
      }
      this.pagination.total = this.dataList.length;
    },

    handleTableChange(pagination, filters, sorter) {
      console.log(pagination);
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
    }
  }
};
</script>
<style lang="scss" scoped>
.page {
  padding: 25px;
  .headerBox {
    display: flex;
    justify-content: space-between;
  }
  .fix-item-wrapper {
    width: 28%;
    display: flex;
    height: 100px;
    background: #ffffff;
    border-radius: 4px;
    padding-top: 0px;
    border: 1px solid #e8e8e8;
    display: flex;
    .childpProjectName {
      margin-bottom: 0px;
      font-size: 14px;
      font-weight: 300;
      color: #9c9c9c;
      text-align: center;
    }
    .childContentName {
      display: flex;
      justify-content: space-between;
      font-size: 24px;
      font-weight: 500;
      color: #333333;
    }

    .fix-item-one {
      height: 50px;
      display: flex;
      align-self: center;
      justify-content: center;
      width: 40%;
      border-right: 1px solid #e8e8e8;
    }
    .fix-item-two {
      width: 60%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .fix-item-two2 {
      width: 40%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .fix-item-name {
      font-size: 18px;
      font-weight: 500;
      color: #222426;
      line-height: 50px;
    }
  }
  .fix-item-wrapper2 {
    width: 70%;
    display: flex;
    height: 100px;
    background: #ffffff;
    border-radius: 4px;
    padding-top: 20px;
    border: 1px solid #e8e8e8;
    display: flex;
    .childpProjectName {
      margin-bottom: 0px;
      font-size: 14px;
      font-weight: 300;
      color: #9c9c9c;
    }
    .childContentName {
      display: flex;
      align-items: center;
      font-size: 24px;
      font-weight: 500;
      color: #333333;
    }
    .fix-item-two {
      padding-left: 35px;
      flex-direction: column;
      width: 50%;
      height: 45px;
      padding-right: 40px;
      display: flex;

      justify-content: space-between;
    }
    .fix-item-name {
      font-size: 18px;
      font-weight: 500;
      color: #222426;
      line-height: 28px;
    }
  }
  .operation {
    padding: 25px 0;
    display: flex;
    justify-content: space-between;
  }
  .tableBox {
  }
  .iconStyle {
    color: var(--primary);
    margin-right: 8px;
  }
}
</style>
